package com.aurora.base.service;

import java.io.Serializable;
import java.util.List;

import javax.persistence.LockModeType;

import org.springframework.transaction.annotation.Transactional;

import com.aurora.base.dao.BaseDao;
import com.aurora.base.dto.Pager;
import com.aurora.base.dto.QueryResult;
import com.aurora.exption.ServiceException;



public abstract class BaseService<T extends Serializable> {
	/**
	 * 该方法由子类实现
	 * 
	 * @return 返回baseDao实例
	 */
	public abstract BaseDao<T> getBaseDao();
	@Transactional
	public boolean save(T entity) {
		boolean flag = false;
		try {
			this.getBaseDao().persist(entity);
			flag = true;
		} catch (Exception e) {
			throw new ServiceException(e);
		}
		return flag;
	}
	@Transactional
	public T update(T entity) {
		try {
			entity = this.getBaseDao().merge(entity);
		} catch (Exception e) {
			throw new ServiceException(e);
		}
		return entity;
	}
	@Transactional
	public void delete(Serializable... entityIds) {
		try {
			this.getBaseDao().remove(entityIds);
		} catch (Exception e) {
			throw new ServiceException(e);
		}
	}

	public T get(Serializable id) {
		try {
			return this.getBaseDao().find(id);
		} catch (Exception e) {
			throw new ServiceException(e);
		}
	}

	public T get(Serializable id, LockModeType lockModeType) {
		try {
			return this.getBaseDao().find(id, lockModeType);
		} catch (Exception e) {
			throw new ServiceException(e);
		}
	}

	public boolean isEntityExist(Serializable entityId) {
		if (null == entityId)
			return false;
		try {
			return this.getBaseDao().isEntityExist(entityId);
		} catch (Exception e) {
			throw new ServiceException(e);
		}
	}

	public QueryResult<T> query(Pager pager) {
		try {
			QueryResult<T> qr = null;
			if (null != pager) {
				qr = this.getBaseDao()
						.query(pager.getOffset(), pager.getSize());
			}
			return qr;
		} catch (Exception e) {
			throw new ServiceException(e);
		}
	}

	public List<T> all() {
		try {
			return this.getBaseDao().list(null);
		} catch (Exception e) {
			throw new ServiceException(e);
		}
	}
}
